package com.lp.exapmle03;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author: lp
 * @create: 2021-06-11 15:01
 * @description: 通过后处理器，自己生成bean,在实例化前执行
 */
public class MyInstantiantionAwarBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		System.out.println("postProcessBeforInstantiation comming");
		//使用cglib代理生成bean
		if(beanClass == Car.class){
			Enhancer enhancer = new Enhancer();
			enhancer.setSuperclass(beanClass);
			enhancer.setCallback(new MethodInterceptor() {
				@Override
				public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
					System.out.println("代理方法执行之前");
					Object object = methodProxy.invokeSuper(o,objects);
					System.out.println("代理方法执行之后");
					return object;
				}
			});
			Car carProxy =(Car)enhancer.create();
			//生成的代理类名：com.lp.exapmle03.Car$$EnhancerByCGLIB$$d047b9a3@14555e0a
			return carProxy;
		}
		return null;
	}

}
